<template>
  <div class="content">
    <div class="header">
      <h3 class="title">用户列表</h3>
      <el-button type="primary" @click="HandleAddNewUser">新建用户</el-button>
      <el-button type="primary" @click="HandleExpUser">导出用户</el-button>
      <el-button type="primary" @click="HandleImpUser">导入用户</el-button>
    </div>
    <div class="table">
      <el-table border :data="UList" style="width: 100%">
        <el-table-column align="center" type="selection" width="60px" />
        <!-- <el-table-column align="center" type="index" label="序号" prop="id" width="60px" /> -->
        <el-table-column align="center" type="index" label="序号" prop="id" width="100px">
          <template #default="scope">
            {{ scope.row.id }}
          </template>
        </el-table-column>

        <el-table-column align="center" label="用户名" prop="nick_name" width="180px" />
        <el-table-column align="center" label="真实姓名" prop="user_name" width="180px" />
        <el-table-column align="center" label="手机号码" prop="tel" width="150px" />

        <!-- 作用域插槽 -->
        <el-table-column align="center" label="状态" prop="status" width="100px">
          <template #default="scope">
            <!-- plain 按钮镂空 -->
            <el-button size="small" :type="scope.row.status ? 'primary' : 'danger'" plain>
              {{ scope.row.status ? '启用' : '禁用' }}
            </el-button>
          </template>
        </el-table-column>

        <el-table-column align="center" label="创建时间" prop="create_date">
          <template #default="scope">
            {{ dateFormat(scope.row.create_date) }}
          </template>
        </el-table-column>

        <el-table-column align="center" label="操作" width="150px">
          <template #default="scope">
            <el-button
              size="small"
              icon="Edit"
              type="primary"
              @click="HandleEditBtnClick(scope.row)"
              text
            >
              编辑
            </el-button>
            <el-button
              size="small"
              icon="Delete"
              type="danger"
              @click="HandleDeleteBtnClick(scope.row.id)"
              v-show="scope.row.status == 1"
              text
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination">
      <!--  -->

      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="usersTotalCount"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>

  <el-dialog
    :visible.sync="dialogUploadSigle"
    v-if="dialogUploadSigle"
    v-model="dialogUploadSigle"
    title="新建用户"
    width="30%"
    center
  >
    <UploadSigle />
  </el-dialog>
</template>

<script setup lang="ts">
// import useListStore from '@/storage/main/system/system.ts'

import { getUserListRequest, delUserByIdRequest } from '@/service/system/system.ts'
import { onMounted, ref, computed } from 'vue'
import { formatUTC, dateFormat } from '@/utils/format'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { localCache } from '@/utils/cache'
import UploadSigle from '@/components/upload/uploadSingle.vue'

// import usePermissions from '@/hooks/usePermissions'

let UList = ref([]) // 异步慢于页面展示

// let UList = computed(() => {
//   return getUsersList(queryInfo)
// })

// 分页
const currentPage = ref(1)
const pageSize = ref(10)
let usersTotalCount = 0

// 导入
const dialogUploadSigle = ref(false)

// const isQuery = usePermissions('users:query')

// 导出用户
function HandleExpUser() {
  fetchUserListData({}, 1)
  console.log('--------------导出用户----------------')
}

// 导入用户
function HandleImpUser() {
  dialogUploadSigle.value = true
  console.log('--------------导入用户----------------')
}

// 每条条数
function handleSizeChange() {
  fetchUserListData()
}

// 翻页
function handleCurrentChange() {
  fetchUserListData()
}

// 默认
const queryInfo = {
  size: pageSize.value,
  page: currentPage.value,
  type: 0,
}

// 4.定义函数, 用于发送网络请求 t=1=导出
function fetchUserListData(formData: any = {}, t: number = 0) {
  // if (!isQuery) return

  console.log('--------------搜索参数拼起来----------------')
  console.log(formData)
  // 1.获取page/size
  // const size = pageSize.value
  // const page = currentPage.value
  // const type = t
  // const pageInfo2 = { size, page, type }

  queryInfo.size = pageSize.value
  queryInfo.page = currentPage.value
  queryInfo.type = t
  // 2.发起网络请求
  const queryInfo2 = { ...queryInfo, ...formData } // 把接收到的兄弟组件的搜索参数拼起来

  if (t == 1) {
    ExpUsersList(queryInfo2)
  } else {
    getUsersList(queryInfo2)
  }
}
function ExpUsersList(queryInfo) {
  // expDowUserListRequest(queryInfo).then((res) => {
  //   // 直接导出
  //   console.log('直接导出')
  // })

  expBlobExcel(queryInfo)
}

function expBlobExcel(queryInfo) {
  axios({
    url: 'http://127.0.0.1:8080/api/user/exp', //请求的真是地址
    method: 'post',
    // params: {
    //   page: 1,
    // },
    data: queryInfo,
    headers: {
      authorization: 'Bearer ' + localCache.getCache('token'),
    },
    responseType: 'blob', //根据后端流文件的格式选择1
  }).then((res) => {
    var blob = new Blob([res.data], {
      type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=utf-8',
    }) //"application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=utf-8"表示的是doc类型，Excel可以选择'application/vnd.ms-excel;charset=utf-8';
    // var contentDisposition = res.headers['content-disposition'] //从response的headers中获取filename, 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
    // var patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*')
    // var result = patt.exec(contentDisposition)
    // var filename = result?.[1]
    console.log('contentDisposition')
    console.log(res.headers)
    console.log(res.headers['content-disposition'])
    var downloadElement = document.createElement('a')
    var href = window.URL.createObjectURL(blob) //创建下载的链接
    downloadElement.style.display = 'none'
    downloadElement.href = href
    // downloadElement.download = filename! //下载后文件名
    // downloadElement.download = 'abc2.xlsx' //下载后文件名 正常
    // downloadElement.download = 'abc2.xls' //下载后文件名 正常
    downloadElement.download = 'abc2.csv' //下载后文件名 csv 正常【更小 更快】
    document.body.appendChild(downloadElement)
    downloadElement.click() //点击下载
    document.body.removeChild(downloadElement) //下载完成移除元素
    window.URL.revokeObjectURL(href) //释放掉blob对象
  })
}

// 表示 也可能是空 queryInfo: any = {}
function getUsersList(queryInfo) {
  getUserListRequest(queryInfo).then((res) => {
    console.log('--------------re222ss----------------')
    console.log(res)
    UList.value = res.data.list
    // UList = res.data.list
    usersTotalCount = res.data.totalRows
  })
}

function HandleDeleteBtnClick(id: number) {
  console.log('delete id is:', id)
  delUserByIdRequest([id]).then((res) => {
    if (res.code == 200) {
      ElMessage.success('删除成功')
      getUsersList(queryInfo)
    }
  })
}

// 加载页面自动执行
onMounted(() => {
  getUsersList(queryInfo)
})

// 新增用户
const emit = defineEmits(['newClick', 'editClick'])
function HandleAddNewUser() {
  // 传给父组件， 再传给兄弟组件
  emit('newClick')
}

function HandleEditBtnClick(row: any) {
  emit('editClick', { row: row })
}

// 把函数暴露出去 让父组件去传递参数并调用（这里是给兄弟组件查询用，兄弟组件search 点击查询后 把事件发送给了父组件，父组件再调用当前函数）
defineExpose({ fetchUserListData })

// 获取数据并展示
// const usersStorge = uListAction.getUserList // 因为是异步的    第一次拿到的是空的
// const usersStorge = storeToRefs(uListAction)

// const uListAction = useListStore()
// // 或者不用返回 这里用computed来监听
// uListAction.UserListAction().then((res) => {
//   console.log('--------------res----------------')
//   console.log(res)
//   UList = res.data.list
// })
</script>

<style lang="less" scoped>
.content {
  margin-top: 20px;
  padding: 20px;
  background-color: #fff;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  margin-bottom: 10px;

  .title {
    font-size: 22px;
  }
}

.table {
  :deep(.el-table__cell) {
    padding: 12px 0;
  }

  .el-button {
    margin-left: 0;
    padding: 5px 8px;
  }
}

.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}
</style>
